<template>
  <div class="top-nav">
    <div class="nav-content">
      <div class="nav-left">
        <!-- 返回按钮和页面标题（替代logo和导航菜单） -->
        <div v-if="showBackButton" class="back-section">
          <el-button text size="large" class="back-button" @click="handleBack">
            <el-icon :size="iconSize">
              <ArrowLeft />
            </el-icon>
          </el-button>
          <span v-if="pageTitle" class="page-title">{{ pageTitle }}</span>
        </div>

        <!-- 普通导航（logo和菜单） -->
        <template v-else>
          <div class="logo" @click="handleLogoClick">
            <el-icon :size="logoIconSize" color="#409EFF">
              <Compass />
            </el-icon>
            <span class="logo-text">删库到跑路研讨中心</span>
          </div>
          <!-- 桌面端导航菜单 -->
          <div class="nav-menu desktop-only">
            <span
              v-for="item in navItems"
              :key="item.key"
              :class="['nav-item', { active: item.key === activeNav }]"
              @click="handleNavClick(item.key)"
            >
              {{ item.label }}
            </span>
          </div>
          <!-- 移动端菜单按钮 -->
          <el-button
            text
            class="mobile-menu-btn mobile-only"
            @click="toggleMobileMenu"
          >
            <el-icon :size="iconSize">
              <Menu />
            </el-icon>
          </el-button>
        </template>
      </div>

      <div class="nav-right">
        <!-- 未登录状态：显示登录注册按钮 -->
        <div v-if="!userAuthStore.isLoggedIn" class="auth-buttons">
          <el-button :size="buttonSize" @click="handleLogin">登录</el-button>
          <el-button type="primary" :size="buttonSize" @click="handleRegister">
            注册
          </el-button>
        </div>

        <!-- 已登录状态：显示通知铃铛和用户信息下拉菜单 -->
        <template v-else>
          <!-- 消息铃铛 -->
          <NotificationBell />

          <!-- 用户信息下拉菜单 -->
          <el-dropdown class="user-dropdown" @command="handleUserCommand">
            <div class="user-info">
              <el-avatar
                :size="avatarSize"
                :src="formatAvatarUrl(userAuthStore.avatar)"
                :icon="UserFilled"
              />
              <span class="username desktop-only">{{
                userAuthStore.nickName || userAuthStore.userName
              }}</span>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人主页</el-dropdown-item>
                <el-dropdown-item command="settings">设置</el-dropdown-item>
                <el-dropdown-item divided command="logout">
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </div>
    </div>

    <!-- 移动端菜单抽屉 -->
    <div
      v-if="showMobileMenu"
      class="mobile-menu-overlay"
      @click="hideMobileMenu"
    >
      <div class="mobile-menu-drawer" @click.stop>
        <div class="mobile-menu-header">
          <span class="menu-title">导航菜单</span>
          <el-button text class="menu-close-btn" @click="hideMobileMenu">
            <el-icon :size="20">
              <Close />
            </el-icon>
          </el-button>
        </div>
        <div class="mobile-menu-items">
          <div
            v-for="item in navItems"
            :key="item.key"
            :class="['mobile-nav-item', { active: item.key === activeNav }]"
            @click="handleMobileNavClick(item.key)"
          >
            {{ item.label }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onBeforeUnmount } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import {
  Compass,
  UserFilled,
  ArrowLeft,
  Menu,
  Close
} from "@element-plus/icons-vue";
import { useUserAuthStore } from "@/store/modules/userAuth";
import NotificationBell from "@/components/NotificationBell.vue";

// Props
interface Props {
  activeNav?: string;
  showBackButton?: boolean;
  pageTitle?: string;
}

const props = withDefaults(defineProps<Props>(), {
  activeNav: "home",
  showBackButton: false,
  pageTitle: ""
});

// Emits
const emit = defineEmits<{
  "nav-click": [nav: string];
  back: [];
}>();

// Composables
const router = useRouter();
const route = useRoute();
const userAuthStore = useUserAuthStore();

// 调试日志
console.log("🔍 TopNavigation - 用户状态检查:", {
  isLoggedIn: userAuthStore.isLoggedIn,
  userId: userAuthStore.userId,
  userName: userAuthStore.userName,
  nickName: userAuthStore.nickName,
  avatar: userAuthStore.avatar,
  token: userAuthStore.token ? "***" + userAuthStore.token.slice(-6) : "无"
});

// 监听头像变化
watch(
  () => userAuthStore.avatar,
  (newAvatar, oldAvatar) => {
    console.log("🔄 顶部导航栏检测到头像变化:", { oldAvatar, newAvatar });
  },
  { immediate: true }
);

// 移动端状态
const isMobile = ref(false);
const showMobileMenu = ref(false);

// 响应式尺寸
const iconSize = computed(() => (isMobile.value ? 20 : 18));
const logoIconSize = computed(() => (isMobile.value ? 20 : 24));
const avatarSize = computed(() => (isMobile.value ? 28 : 32));
const buttonSize = computed(() => (isMobile.value ? "small" : "small"));

// 导航菜单项
const navItems = [
  { key: "home", label: "首页" },
  { key: "creation", label: "创作" },
  { key: "put-forward-bug", label: "提BUG" },
  { key: "about-us", label: "关于" }
];

// 检测移动端
const checkMobile = () => {
  isMobile.value = window.innerWidth <= 768;
};

// 方法
const handleLogoClick = () => {
  router.push("/user/home");
};

const handleBack = () => {
  emit("back");
};

const handleNavClick = (nav: string) => {
  emit("nav-click", nav);

  // 默认导航处理
  switch (nav) {
    case "home":
      router.push("/user/home");
      break;
    case "creation":
      // 创作按钮跳转到发布文章页面
      router.push("/user/article/publish");
      break;
    case "put-forward-bug":
    case "about-us":
      ElMessage.info(
        `${navItems.find(item => item.key === nav)?.label}功能开发中...`
      );
      break;
    default:
      break;
  }
};

// 移动端菜单相关方法
const toggleMobileMenu = () => {
  showMobileMenu.value = !showMobileMenu.value;
};

const hideMobileMenu = () => {
  showMobileMenu.value = false;
};

const handleMobileNavClick = (nav: string) => {
  handleNavClick(nav);
  hideMobileMenu();
};

const handleLogin = () => {
  router.push("/user/login");
};

const handleRegister = () => {
  router.push("/user/register");
};

// 格式化头像URL
const formatAvatarUrl = (url: string): string => {
  console.log("🖼️ 顶部导航栏头像URL:", url);
  if (!url) return "";

  // 如果已经是完整URL，直接返回
  if (url.startsWith("http://") || url.startsWith("https://")) {
    return url;
  }

  // 如果是相对路径，添加基础URL
  const baseURL = import.meta.env.DEV
    ? "http://localhost:8081"
    : "http://localhost:8081";
  const fullUrl = baseURL + url;
  console.log("🖼️ 格式化后的头像URL:", fullUrl);
  return fullUrl;
};

const handleUserCommand = (command: string) => {
  switch (command) {
    case "profile":
      // 强制跳转到个人主页，确保能正常导航
      router.push(`/user/profile/${userAuthStore.userId}`);
      break;
    case "settings":
      router.push("/user/profile-edit");
      break;
    case "logout":
      handleLogout();
      break;
    default:
      break;
  }
};

const handleLogout = async () => {
  try {
    await userAuthStore.logout();
    ElMessage.success("退出登录成功");
    router.push("/user/login");
  } catch (error) {
    console.error("退出登录失败:", error);
    ElMessage.error("退出登录失败");
  }
};

// 生命周期钩子
onMounted(() => {
  checkMobile();
  window.addEventListener("resize", checkMobile);
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", checkMobile);
});
</script>

<style lang="scss">
// 设计系统变量
$primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
$accent-gradient: linear-gradient(135deg, #ff6b6b, #ee5a24);
$glass-bg: rgb(255 255 255 / 10%);
$glass-border: rgb(255 255 255 / 20%);
$text-primary: white;
$text-secondary: rgb(255 255 255 / 85%);
$text-muted: rgb(255 255 255 / 70%);
$shadow-light: 0 4px 12px rgb(0 0 0 / 10%);
$shadow-medium: 0 6px 20px rgb(0 0 0 / 15%);
$transition-smooth: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

@use "@/styles/user-theme.scss" as *;

// 移动端媒体查询 - 使用更高优先级
@media screen and (width <= 767px) {
  .desktop-only,
  .nav-menu.desktop-only,
  .username.desktop-only {
    display: none !important;
    visibility: hidden !important;
  }

  .mobile-only,
  .mobile-menu-btn.mobile-only {
    display: inline-flex !important;
    visibility: visible !important;
  }
}

// 移动端适配 - 强制覆盖所有样式
@media screen and (width <= 767px) {
  // 强制隐藏桌面端元素
  .top-nav .nav-menu.desktop-only,
  .top-nav .username.desktop-only {
    display: none !important;
    visibility: hidden !important;
    opacity: 0 !important;
  }

  // 强制显示移动端元素
  .top-nav .mobile-menu-btn.mobile-only {
    display: inline-flex !important;
    visibility: visible !important;
    opacity: 1 !important;
  }

  .top-nav {
    position: fixed !important;

    .nav-content {
      height: 56px !important;
      padding: 0 16px !important;

      .nav-left {
        gap: 16px !important;

        .back-section {
          gap: 8px !important;

          .back-button {
            padding: 6px 8px !important;
          }

          .page-title {
            font-size: 16px !important;
          }
        }

        .logo {
          padding: 6px 12px !important;

          .logo-text {
            font-size: 18px !important;
          }
        }

        .mobile-menu-btn {
          padding: 6px 8px !important;
        }
      }

      .nav-right {
        gap: 8px !important;

        .auth-buttons {
          gap: 8px !important;

          .el-button {
            padding: 6px 12px !important;
            font-size: 13px !important;
            border-radius: 16px !important;
          }
        }

        .user-dropdown .user-info {
          padding: 6px 12px !important;
          border-radius: 20px !important;

          .el-avatar {
            border-width: 1px !important;
          }
        }
      }
    }
  }
}

// iPhone XR 专用优化 (414px宽度)
@media (width <= 414px) {
  .top-nav {
    padding-right: env(safe-area-inset-right);

    /* 考虑安全区域 */
    padding-left: env(safe-area-inset-left);

    .nav-content {
      padding-right: max(16px, env(safe-area-inset-right));
      padding-left: max(16px, env(safe-area-inset-left));
    }
  }

  .mobile-search-bar {
    padding-right: max(16px, env(safe-area-inset-right));
    padding-left: max(16px, env(safe-area-inset-left));
  }

  .mobile-menu-drawer {
    padding-right: env(safe-area-inset-right);
  }
}

// 桌面端显示/隐藏控制
.desktop-only {
  display: block !important;
}

// 移动端显示/隐藏控制
.mobile-only {
  display: none !important;
}

// 基础导航栏样式
.top-nav {
  position: sticky;
  top: 0;
  z-index: 1000;
  background: $primary-gradient;
  border-bottom: 1px solid $glass-border;
  box-shadow: $shadow-medium;
  backdrop-filter: blur(20px);

  .nav-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    max-width: 1400px;
    height: 64px;
    padding: 0 32px;
    margin: 0 auto;

    // 左边内容居中于整个导航栏
    .nav-left {
      display: flex;
      flex: 1;
      gap: 40px;
      align-items: center;
      justify-content: center;

      .back-section {
        display: flex;
        gap: 12px;
        align-items: center;

        .back-button {
          padding: 8px 12px;
          color: $text-primary;
          border-radius: 8px;
          transition: $transition-smooth;

          &:hover {
            background: $glass-bg;
          }
        }

        .page-title {
          font-size: 18px;
          font-weight: 600;
          color: $text-primary;
        }
      }

      .logo {
        display: flex;
        gap: 12px;
        align-items: center;
        padding: 8px 16px;
        cursor: pointer;
        border-radius: 12px;
        transition: $transition-smooth;

        &:hover {
          background: $glass-bg;
          transform: translateY(-1px);
        }

        .logo-text {
          font-size: 20px;
          font-weight: 700;
          color: $text-primary;
          text-shadow: 0 1px 2px rgb(0 0 0 / 10%);
        }
      }

      .nav-menu {
        display: flex;
        gap: 8px;

        .nav-item {
          padding: 10px 16px;
          font-size: 14px;
          font-weight: 500;
          color: $text-secondary;
          cursor: pointer;
          border-radius: 8px;
          transition: $transition-smooth;

          &:hover {
            color: $text-primary;
            background: $glass-bg;
            transform: translateY(-1px);
          }

          &.active {
            color: $text-primary;
            background: $glass-bg;
            box-shadow: $shadow-light;
          }
        }
      }

      .mobile-menu-btn {
        padding: 8px;
        color: $text-primary;
        border-radius: 8px;
        transition: $transition-smooth;

        &:hover {
          background: $glass-bg;
        }
      }
    }

    .nav-right {
      display: flex;
      gap: 16px;
      align-items: center;

      .auth-buttons {
        display: flex;
        gap: 12px;

        .el-button {
          padding: 8px 20px;
          font-size: 14px;
          font-weight: 500;
          color: $text-primary;
          background: $glass-bg;
          border: 1px solid $glass-border;
          border-radius: 20px;
          backdrop-filter: blur(10px);
          transition: $transition-smooth;

          &:hover {
            background: rgb(255 255 255 / 20%);
            border-color: rgb(255 255 255 / 40%);
            box-shadow: $shadow-light;
            transform: translateY(-1px);
          }

          &.el-button--primary {
            background: $accent-gradient;
            border: none;

            &:hover {
              background: linear-gradient(135deg, #ff5252, #e53e3e);
              box-shadow: 0 6px 20px rgb(238 90 36 / 40%);
            }
          }
        }
      }

      .user-dropdown {
        .user-info {
          display: flex;
          gap: 10px;
          align-items: center;
          padding: 8px 16px;
          cursor: pointer;
          background: $glass-bg;
          border: 1px solid $glass-border;
          border-radius: 25px;
          backdrop-filter: blur(10px);
          transition: $transition-smooth;

          &:hover {
            background: rgb(255 255 255 / 20%);
            border-color: rgb(255 255 255 / 30%);
            box-shadow: $shadow-light;
            transform: translateY(-1px);
          }

          .el-avatar {
            border: 2px solid $glass-border;
            transition: all 0.3s ease;
          }

          .username {
            font-size: 14px;
            font-weight: 500;
            color: $text-primary;
            text-shadow: 0 1px 2px rgb(0 0 0 / 10%);
          }
        }
      }
    }
  }
}

// 移动端菜单抽屉
.mobile-menu-overlay {
  position: fixed;
  inset: 0;
  z-index: 2000;
  background: rgb(0 0 0 / 50%);
  backdrop-filter: blur(4px);

  .mobile-menu-drawer {
    position: absolute;
    top: 0;
    right: 0;
    width: 280px;
    height: 100vh;
    background: white;
    box-shadow: -4px 0 20px rgb(0 0 0 / 15%);
    transform: translateX(0);
    transition: transform 0.3s ease;

    .mobile-menu-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 20px;
      border-bottom: 1px solid #f0f2f5;

      .menu-title {
        font-size: 18px;
        font-weight: 600;
        color: #1f2937;
      }

      .menu-close-btn {
        padding: 8px;
        color: #6b7280;
        border-radius: 8px;
        transition: $transition-smooth;

        &:hover {
          background: #f3f4f6;
        }
      }
    }

    .mobile-menu-items {
      padding: 20px 0;

      .mobile-nav-item {
        display: flex;
        align-items: center;
        padding: 16px 20px;
        font-size: 16px;
        font-weight: 500;
        color: #374151;
        cursor: pointer;
        transition: $transition-smooth;

        &:hover {
          color: #1e80ff;
          background: #f9fafb;
        }

        &.active {
          color: #1e80ff;
          background: #eff6ff;
          border-right: 3px solid #1e80ff;
        }
      }
    }
  }
}
</style>
